﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using System.IO;


namespace ContourStrikesAgain.PrevalueSourceTypes
{
    public class GetValuesFromTextFile : FieldPreValueSourceType 
    {
        [Umbraco.Forms.Core.Attributes.Setting("TextFile", 
            description = "File containing the prevalues (seperated by linebreak)", 
            control = "Umbraco.Forms.Core.FieldSetting.File")]
        public string TextFile { get; set; }

        public GetValuesFromTextFile()
        {
            this.Id = new Guid("E0DCB4EA-B05E-47D9-B68C-2AA6D0EFDB1A");
            this.Name = "Get values from textfile";
            this.Description = "Upload textfile that contains the prevalues (seperated by linebreak)";
        }

        public override List<PreValue> GetPreValues(Field field)
        {
            List<PreValue> result = new List<PreValue>();

            try
            {
                int sort = 0;

                TextReader tr = new StreamReader(HttpContext.Current.Server.MapPath(TextFile));
                string[] values = tr.ReadToEnd().Split('\n');

                foreach (string value in values)
                {
                    if (!string.IsNullOrEmpty(value.Trim()))
                    {
                        PreValue pv = new PreValue();
                        pv.Id = sort;
                        pv.Value = value;
                        if (field != null)
                        {
                            pv.Field = field.Id;
                        }
                        pv.SortOrder = sort;
                        result.Add(pv);
                        sort++;
                    }
                }
            }
            catch (Exception ex)
            {
                Umbraco.Forms.Data.LogHelper.Error("Get values from textfile provider: " + ex.ToString());
            }

            return result;
        }

        public override List<Exception> ValidateSettings()
        {
            List<Exception> exs = new List<Exception>();

            if (string.IsNullOrEmpty(TextFile))
                exs.Add(new Exception("'TextFile' setting not filled out'"));

            return exs;
        }

    }
}